package com.yzd.netmonitor.web;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class JsonBinder {

	private static final Logger log = LoggerFactory.getLogger(JsonBinder.class);

	public static String toJson(Object obj) {

		return JSON.toJSONString(obj);
	}

	public static <T> T fromJson(String json, Class<T> clazz) {

		if (StringUtils.isEmpty(json)) {
			return null;
		}
		try {
			//json转对象(json,类)
			return JSON.parseObject(json, clazz);
		} catch (Exception e) {
			log.error("parse from json string error:", e);
		}

		return null;
	}

	public static <T> List<T> getListFromJson(String json, Class<T> clazz) {

		if (StringUtils.isEmpty(json)) {
			return null;
		}
		try {
			return JSON.parseArray(json, clazz);
		} catch (Exception e) {
			log.error("parse list from json error:", e);
		}
		return null;
	}

	public static <T> Map<String, T> getMapFromJson(String json, Class<T> clazz) {

		if (StringUtils.isEmpty(json)) {
			return null;
		}
		try {
			return JSON.parseObject(json, new TypeReference<Map<String, T>>() {
			});
		} catch (Exception e) {
			log.error("parse map from json error:", e);
		}
		return null;
	}

	public static String parseDate(Date date) {

		if (date == null) {
			return null;
		}
		return JSON.toJSONString(date, SerializerFeature.WriteDateUseDateFormat);
	}

	public static String parseDate(Date date, String format) {

		if (date == null) {
			return null;
		}
		if (StringUtils.isEmpty(format)) {
			return parseDate(date);
		}
		return JSON.toJSONStringWithDateFormat(date, format,
				SerializerFeature.WriteDateUseDateFormat);
	}

	public static JSONObject getJsonObject(String data) {

		return JSON.parseObject(data);
	}
}
